package com.git.smp.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.git.smp.core.ResponseMessage;
import com.git.smp.dao.RolePermissionMapper;
import com.git.smp.entity.RolePermissionKey;
import com.git.smp.entity.RolePermissionKeyExtend;
import com.git.smp.entity.SmpPermission;

@RestController
@RequestMapping("/rolePermission")
public class SmpRolePermissionController {
	
	Logger logger = LoggerFactory.getLogger(SmpPermissionController.class);
	
	@Autowired
	RolePermissionMapper rolePermissionMapper;
	
	//维护角色权限信息
	@RequestMapping("/updateRolePermission")
	@Transactional
	public ResponseMessage<?> updateRolePermission(
			@RequestBody RolePermissionKeyExtend rolePermissionKeyExtend){
		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("角色权限信息维护成功！");
		
		int code = rolePermissionMapper.deleteByPrimaryKey(rolePermissionKeyExtend.getId());
		RolePermissionKey rolePermissionKey = new RolePermissionKey();
		rolePermissionKey.setRoleId(rolePermissionKeyExtend.getId());
		
		for (String permissionId : rolePermissionKeyExtend.getPermissionIdList()) {
			rolePermissionKey.setPermissionId(permissionId);
			rolePermissionMapper.insert(rolePermissionKey);
		}
		
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
	
	//根据角色ID获取对应权限
	@RequestMapping("getPermissionInfoByRoleId")
	public ResponseMessage<List<String>> getPermissionInfoByRoleId(
			@RequestParam String roleId){
		ResponseMessage<List<String>> responseMessage = new ResponseMessage<List<String>>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("角色权限信息查询成功！");
		
		List<String> listPermissionId = rolePermissionMapper.getPermissionInfoByRoleId(roleId);
		if(listPermissionId == null) {
			responseMessage.setCode("0001");
			responseMessage.setMessage("该角色权限信息查询条数为零！");
		}
			
		responseMessage.setExtend(listPermissionId);
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
}
